package cn.example.listandrecycleruit;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

public class FruitAdapter extends ArrayAdapter<Fruit>{

    private int resourceId;

    public FruitAdapter(@NonNull Context context, int resource, @NonNull List<Fruit> objects) {
        super(context, resource, objects);
        /*
         获取资源id
         */
        this.resourceId=resource;
    }

    /**
     *
     * @param position
     * @param convertView 缓冲提供的类
     * @param parent
     * @return
     */
    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        /*
         拿到资源

        Fruit item = getItem(position);*/
        /*
            false : 一旦有了父布局之后,就不能添加到istview中
            动态操作布局类型
         */
        /*View view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);
        img_fruit=view.findViewById(R.id.img_fruit);
        tv_fruit=view.findViewById(R.id.tv_fruit);
        img_fruit.setImageResource(item.getImgId());
        tv_fruit.setText(item.getName());
        return view;*/

        /**
         * 优化后的代码
         */
        Fruit item = getItem(position);
        ViewHolder viewHolder;
        View view;
        if (convertView == null) {
            view=LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
            viewHolder=new ViewHolder();
            viewHolder.img_fruit= view.findViewById(R.id.img_fruit);
            viewHolder.tv_fruit=view.findViewById(R.id.tv_fruit);
            //使用setTag() 临时保存数据
            view.setTag(viewHolder);
        }else{
            view=convertView;//获取临时数据
            viewHolder =(ViewHolder) view.getTag();
        }
        viewHolder.tv_fruit.setText(item.getName());
        viewHolder.img_fruit.setImageResource(item.getImgId());
        return  view;
    }

    class ViewHolder{
        ImageView img_fruit;
        TextView tv_fruit;
    }
}
